from  db.dao.coach import Coach
from datetime import datetime
from sqlalchemy.ext.declarative import DeclarativeMeta
import json,copy
d = {'a': 1, 'b': {'c': 2}, 'd': ['hi', {'foo': 'bar'}]}
def objfdic(d):
    top = type('new', (object,), d)
    seqs = tuple, list, set, frozenset
    for i, j in d.items():
        if isinstance(j, dict):
            setattr(top, i, objfdic(j))
        elif isinstance(j, seqs):
            setattr(top, i,
                type(j)(objfdic(sj) if isinstance(sj, dict) else sj for sj in j))
        else:
            setattr(top, i, j)
    return top


def load_json_array_to_object(json_array,obj):
    #print(type(json_array)) #类型为list json对象list 转换了指定对象list
    obj_list = []
    #print(obj.__class__)
    for json_obj in json_array: #遍历json list 循环出的每一个json对象转换成对应的指定对象（例如 Coach）
        new_obj = copy.deepcopy(obj) #深拷贝
        print(type(json_obj))
        if isinstance(obj.__class__, DeclarativeMeta): #如果类型课定义的类型 元数据
            #for x in dir(obj) 得到全部属性 方法的名字
            for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata' and x!='registry']:
                #print(field) #与数据库字段名对应的对象属性名
                data = json_obj[field] #根据字段名获取值
                try:
                    if isinstance(data, datetime):
                        data = data.strftime('%Y-%m-%d %H:%M:%S')
                    #json.dumps(data)  # this will fail on non-encodable values, like other classes
                    setattr(new_obj,field,data) #setattr 设置值 给new_obj对象设置field字段的值为data
                except TypeError:
                    setattr(new_obj,field,None)
            obj_list.append(new_obj)
    return obj_list


def load_json_to_object(json_obj,obj):
    #print(type(json_array)) #类型为list json对象list 转换了指定对象list
    #print(obj.__class__)
    #for json_obj in json_obj: #遍历json list 循环出的每一个json对象转换成对应的指定对象（例如 Coach）
    new_obj = copy.deepcopy(obj) #深拷贝
    print(type(json_obj))
    if isinstance(obj.__class__, DeclarativeMeta): #如果类型课定义的类型 元数据
        #for x in dir(obj) 得到全部属性 方法的名字
        for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata' and x!='registry' and x!='format_str']:
            #print(field) #与数据库字段名对应的对象属性名
            data = json_obj[field] #根据字段名获取值
            try:
                if isinstance(data, datetime):
                    data = data.strftime('%Y-%m-%d %H:%M:%S')
                #json.dumps(data)  # this will fail on non-encodable values, like other classes
                setattr(new_obj,field,data) #setattr 设置值 给new_obj对象设置field字段的值为data
            except TypeError:
                setattr(new_obj,field,None)
    return new_obj



#print(result.b.c)